#!/usr/bin/env python

import os.path

from PyXSE.Database import Database
from PyXSE.Table import DuplicateError
from pyfileutils import create_folder, delete_folder

test_dir = "folder_to_test_on"
def get_password_setter(p):
    def password_setter(r):
        r['password'] = p
    return password_setter
if os.path.isdir(test_dir):
    delete_folder(test_dir)
create_folder(test_dir)
print "Creating Database"
db = Database(test_dir)
print "Creating 'users' Table"
db.create_table('users', ['username', 'password', 'fullname'],
                         ['str', 'str', 'str'],
                         unique=['username'])
print "Inserting Rows"
db.insert('users', ['charlie', 'bicycle', 'Charlie Gunyon'])
db.insert('users', ['tara', 'tricycle', 'Tara Gunyon'])
try:
    print "Attempting to insert a duplicate row"
    db.insert('users', ['charlie', 'motorcycle', 'Maurice Gunyon'])
    raise Exception("UNIQUE KEY constraint violated!")
except DuplicateError, e:
    print "UNIQUE KEY constraint preserved!"
    pass # this is actually what we want
print "Verifying database contents"
assert set([x['username'] for x in db.select('users')]) == \
       set(['tara', 'charlie'])
print "Deleting a row"
db.delete('users', where=[lambda x: x['username'] == 'charlie'])
assert [x['username'] for x in db.select('users')] == ['tara']
print "Updating a row"
db.update('users', where=[lambda x: x['username'] == 'tara'],
                   set=[get_password_setter('motorcycle')])
assert [x['password'] for x in db.select('users')] == ['motorcycle']
print "Passed!"
delete_folder(test_dir)
